import path, { resolve } from 'path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
// import externalGlobals from 'rollup-plugin-external-globals'
import vueSetupExtend from 'vite-plugin-vue-setup-extend'
import eslintPlugin from 'vite-plugin-eslint'
import AutoImport from 'unplugin-auto-import/vite' // 无需导入ref,reactive,watch等API <由于与cdn冲突，现已删除自动导入配置代码>
import Components from 'unplugin-vue-components/vite' // 详情可见https://github.com/antfu/unplugin-vue-components
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { visualizer } from 'rollup-plugin-visualizer'
import { Plugin as importToCDN, autoComplete } from 'vite-plugin-cdn-import'
import svgLoader from 'vite-svg-loader'
import progress from 'vite-plugin-progress'
import colors from 'picocolors'

const pathSrc = path.resolve(__dirname, 'src')
export default defineConfig({
  root: process.cwd(),
  base: './',
  publicDir: 'public',
  cacheDir: 'node_modules/.vite',
  assetsInclude: '',
  logLevel: 'info',
  clearScreen: true,
  plugins: [
    vue({ reactivityTransform: true }),
    vueJsx(),
    eslintPlugin({
      include: ['src/**/*.js', 'src/*.js', 'src/**/*.vue', 'src/*.vue', 'src/**/*.ts', 'src/*.ts'],
    }),
    vueSetupExtend(),
    AutoImport({
      dts: false,
      resolvers: [
        ElementPlusResolver(),
      ],
    }),
    Components({
      resolvers: [
        ElementPlusResolver(),
      ],
      dts: false,
    }),
    svgLoader(),
    progress({
      format: `${colors.green(colors.bold('Bouilding'))} ${colors.cyan('[:bar]')} :percent`,
      total: 200,
      width: 60,
      complete: '=',
      incomplete: '',
    }),
    visualizer({ open: false }),
    importToCDN({ // 生产环境使用cdn减少项目体积，提升打包速度
      modules: [
        autoComplete('vue'),
        {
          name: 'vue',
          var: 'Vue',
          path: 'https://unpkg.com/vue@3.2.45/dist/vue.global.prod.js',
        },
        {
          name: 'vue-router',
          var: 'VueRouter',
          path: 'https://unpkg.com/vue-router@4.1.6/dist/vue-router.global.prod.js',
        },
        {
          name: 'element-plus',
          var: 'ElementPlus',
          path: 'https://unpkg.com/element-plus@2.2.27/dist/index.full.js',
          // css: 'https://unpkg.com/element-plus/dist/index.css',
        },
        {
          name: 'vue-demi',
          var: 'VueDemi',
          path: 'https://cdn.bootcdn.net/ajax/libs/vue-demi/0.13.1/index.iife.js',
        },
        {
          name: 'pinia',
          var: 'Pinia',
          path: 'https://cdn.bootcdn.net/ajax/libs/pinia/2.0.14/pinia.iife.prod.min.js',
        },
      ],
    }),
  ],
  envPrefix: 'ENV_',
  resolve: {
    alias: {
      '@': pathSrc,
    },
    extensions: ['.js', '.jsx', '.vue', '.json', '.ts', '.tsx'],
  },
  json: {
    // 是否支持从 .json 文件中进行按名导入
    namedExports: true,
    stringify: false,
  },
  // 继承自 esbuild 转换选项，最常见的用例是自定义 JSX
  esbuild: {
    jsxFactory: 'h',
    jsxFragment: 'Fragment',
    jsxInject: 'import Vue from \'vue\'',
  },
  css: {
    preprocessorOptions: {
      // 定义全局变量
      less: {
        additionalData: `@import "${resolve(
          __dirname,
          'src/styles/variables.less',
        )}";`,
        javascriptEnabled: true,
      },
    },
  },
  server: {
    host: 'localhost',
    https: false,
    cors: true, // 为开发服务器配置 CORS , 默认启用并允许任何源
    open: true,
    strictPort: false, // 设为true时端口被占用则直接退出，不会尝试下一个可用端口
    hmr: true,
    // proxy: {
    //   '': {
    //     target: '',
    //     changeOrigin: true,
    //     rewrite: (pathapi) =>
    //       pathapi.replace(/^\/renren-fast/, ''),
    //   },
    // },
  },
  build: {
    target: 'modules',
    outDir: 'dist',
    assetsDir: 'static',
    assetsInlineLimit: 4096,
    cssCodeSplit: true,
    sourcemap: false,
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,
      },
    },
    write: true,
    emptyOutDir: true,
    reportCompressedSize: false,
    rollupOptions: {
      external: ['vue', 'vue-router', 'element-plus'],
      // plugins: [
      //   externalGlobals({
      //     vue: 'Vue',
      //     'element-plus': 'ElementPlus',
      //     // 👇 配置 vue-demi 全局变量 👇
      //     'vue-demi': 'VueDemi',
      //   }),
      // ],
      output: {
        chunkFileNames: 'static/js/[name]-[hash].js',
        entryFileNames: 'static/js/[name]-[hash].js',
        assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
        manualChunks(id: string) {
          if (id.includes('node_modules')) {
            return id.toString().split('node_modules/')[1].split('/')[0].toString()
          }
          return ''
        },
      },
    },
  },
})
